<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据库名" prop="dbName">
        <el-input
          v-model="queryParams.dbName"
          placeholder="请输入数据库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务器" prop="serverId">
        <el-select v-model="queryParams.serverId" placeholder="请选择服务器" clearable>
          <el-option
            v-for="item in serverOptions"
            :key="item.serverId"
            :label="item.serverName"
            :value="item.serverId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dbmanagement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dbmanagement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dbmanagement:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="databaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据库ID" align="center" prop="dbId" v-if="false" />
      <el-table-column label="数据库名称" align="center" prop="dbName" />
      <el-table-column label="服务器" align="center" prop="serverName" />
      <el-table-column label="数据库类型" align="center" prop="dbType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.dbType === 'mysql'">MySQL</el-tag>
          <el-tag v-else-if="scope.row.dbType === 'sqlserver'" type="success">SQL Server</el-tag>
          <el-tag v-else-if="scope.row.dbType === 'oracle'" type="warning">Oracle</el-tag>
          <el-tag v-else-if="scope.row.dbType === 'postgresql'" type="info">PostgreSQL</el-tag>
          <el-tag v-else type="danger">{{scope.row.dbType}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handleTest(scope.row)"
            v-hasPermi="['system:dbmanagement:test']"
          >测试连接</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dbmanagement:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dbmanagement:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="backup" icon="el-icon-download"
                v-hasPermi="['system:dbmanagement:backup']">备份</el-dropdown-item>
              <el-dropdown-item command="restore" icon="el-icon-upload"
                v-hasPermi="['system:dbmanagement:restore']">还原</el-dropdown-item>
              <el-dropdown-item command="tables" icon="el-icon-menu">查看表</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="服务器" prop="serverId">
          <el-select v-model="form.serverId" placeholder="请选择服务器" @change="handleServerChange">
            <el-option
              v-for="item in serverOptions"
              :key="item.serverId"
              :label="item.serverName"
              :value="item.serverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbType">
          <el-select v-model="form.dbType" placeholder="请选择数据库类型" @change="handleDbTypeChange">
            <el-option label="MySQL" value="mysql" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="PostgreSQL" value="postgresql" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接地址" prop="dbHost">
          <el-input v-model="form.dbHost" placeholder="请输入连接地址" />
        </el-form-item>
        <el-form-item label="端口" prop="dbPort">
          <el-input v-model="form.dbPort" placeholder="请输入端口" />
        </el-form-item>
        <el-form-item label="数据库实例名" prop="dbInstance">
          <el-input v-model="form.dbInstance" placeholder="请输入数据库实例名" />
        </el-form-item>
        <el-form-item label="用户名" prop="dbUsername">
          <el-input v-model="form.dbUsername" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="dbPassword">
          <el-input v-model="form.dbPassword" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="备份路径" prop="backupPath">
          <el-input v-model="form.backupPath" placeholder="请输入备份路径" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 备份历史对话框 -->
    <el-dialog title="备份历史" :visible.sync="backupHistoryOpen" width="800px" append-to-body>
      <el-table :data="backupHistoryList" height="400">
        <el-table-column label="备份ID" align="center" prop="backupId" />
        <el-table-column label="备份文件名" align="center" prop="fileName" />
        <el-table-column label="备份大小" align="center" prop="fileSize">
          <template slot-scope="scope">
            {{ formatSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="备份时间" align="center" prop="backupTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.backupTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-upload"
              @click="handleRestore(scope.row)"
            >还原</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 数据表列表对话框 -->
    <el-dialog title="数据表列表" :visible.sync="tablesOpen" width="800px" append-to-body>
      <el-table :data="tablesList" height="400">
        <el-table-column label="表名" align="center" prop="tableName" />
        <el-table-column label="表注释" align="center" prop="tableComment" />
        <el-table-column label="记录数" align="center" prop="rowCount" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listDatabase, getDatabase, delDatabase, addDatabase, updateDatabase, testDatabaseConnection, 
  listDatabaseTables, backupDatabase, restoreDatabase, getBackupHistory } from "@/api/system/dbmanagement";
import { listServer } from "@/api/system/server";

export default {
  name: "DbManagement",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库管理表格数据
      databaseList: [],
      // 服务器选项
      serverOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示备份历史弹出层
      backupHistoryOpen: false,
      // 备份历史列表
      backupHistoryList: [],
      // 是否显示数据表列表弹出层
      tablesOpen: false,
      // 数据表列表
      tablesList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: undefined,
        serverId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 当前操作的数据库ID
      currentDbId: undefined,
      // 数据库类型默认端口映射
      defaultPorts: {
        mysql: "3306",
        sqlserver: "1433",
        oracle: "1521",
        postgresql: "5432"
      },
      // 表单校验
      rules: {
        dbName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" }
        ],
        serverId: [
          { required: true, message: "服务器不能为空", trigger: "change" }
        ],
        dbType: [
          { required: true, message: "数据库类型不能为空", trigger: "change" }
        ],
        dbHost: [
          { required: true, message: "连接地址不能为空", trigger: "blur" }
        ],
        dbPort: [
          { required: true, message: "端口不能为空", trigger: "blur" }
        ],
        dbUsername: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getServerOptions();
  },
  methods: {
    /** 查询数据库列表 */
    getList() {
      this.loading = true;
      listDatabase(this.queryParams).then(response => {
        this.databaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取服务器选项 */
    getServerOptions() {
      listServer().then(response => {
        this.serverOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dbId: undefined,
        dbName: undefined,
        serverId: undefined,
        dbType: 'mysql',
        dbHost: undefined,
        dbPort: "3306", // 默认为MySQL端口
        dbInstance: undefined,
        dbUsername: undefined,
        dbPassword: undefined,
        backupPath: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dbId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dbId = row.dbId || this.ids[0];
      getDatabase(dbId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据库";
      });
    },
    /** 数据库类型变更处理 */
    handleDbTypeChange(value) {
      // 根据数据库类型设置默认端口
      if (this.defaultPorts[value]) {
        this.form.dbPort = this.defaultPorts[value];
      }
      // 根据服务器设置IP地址
      if (this.form.serverId) {
        const server = this.serverOptions.find(item => item.serverId === this.form.serverId);
        if (server && server.serverIp) {
          this.form.dbHost = server.serverIp;
        }
      }
    },
    /** 服务器选择变更处理 */
    handleServerChange(value) {
      const server = this.serverOptions.find(item => item.serverId === value);
      if (server && server.serverIp) {
        this.form.dbHost = server.serverIp;
      }
    },
    /** 测试连接按钮操作 */
    handleTest(row) {
      const dbId = row.dbId;
      testDatabaseConnection(dbId).then(() => {
        this.$modal.msgSuccess("连接测试成功");
      });
    },
    /** 下拉菜单操作 */
    handleCommand(command, row) {
      const dbId = row.dbId;
      this.currentDbId = dbId;
      if (command === 'backup') {
        // 备份数据库
        this.$modal.confirm('确认要备份数据库"' + row.dbName + '"吗？').then(() => {
          return backupDatabase(dbId);
        }).then(() => {
          this.$modal.msgSuccess("备份成功");
        }).catch(() => {});
      } else if (command === 'restore') {
        // 查询备份历史并打开还原对话框
        getBackupHistory(dbId).then(response => {
          this.backupHistoryList = response.data;
          this.backupHistoryOpen = true;
        });
      } else if (command === 'tables') {
        // 查询数据表列表
        listDatabaseTables(dbId).then(response => {
          this.tablesList = response.data;
          this.tablesOpen = true;
        });
      }
    },
    /** 执行还原操作 */
    handleRestore(row) {
      this.$modal.confirm('确认要还原数据库为备份"' + row.fileName + '"吗？还原操作将覆盖当前数据库内容。').then(() => {
        const data = {
          dbId: this.currentDbId,
          backupId: row.backupId
        };
        return restoreDatabase(data);
      }).then(() => {
        this.backupHistoryOpen = false;
        this.$modal.msgSuccess("还原成功");
      }).catch(() => {});
    },
    /** 下载备份文件 */
    handleDownload(row) {
      // 实现下载备份文件的逻辑
      this.$modal.msgInfo("正在下载备份文件：" + row.fileName);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dbId !== undefined) {
            updateDatabase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDatabase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dbIds = row.dbId || this.ids;
      this.$modal.confirm('是否确认删除数据库编号为"' + dbIds + '"的数据项？').then(function() {
        return delDatabase(dbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 格式化文件大小
    formatSize(size) {
      if (!size) return '0 B';
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      let index = 0;
      while (size >= 1024 && index < units.length - 1) {
        size /= 1024;
        index++;
      }
      return size.toFixed(2) + ' ' + units[index];
    }
  }
};
</script> 